#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>
#include <QDebug>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    client = new QTcpSocket(this);
    connect(client, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
    connect(client, SIGNAL(connected()), this, SLOT(slotConnected()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QString ip = ui->lineEdit_ip->text();
    int port = ui->lineEdit_port->text().toInt();
    client->abort();
    client->connectToHost(QHostAddress(ip), port);
}

void MainWindow::on_pushButton_2_clicked()
{
    QString message = ui->lineEdit_message->text();
    client->write(message.toUtf8());
    ui->textBrowser->append("我：\n  " + message);
}

void MainWindow::slotReadyRead(){
    QByteArray bytes = client->readAll();
    ui->textBrowser->append("服务器：\n  " + QString::fromUtf8(bytes));
}

void MainWindow::slotConnected()
{
    QMessageBox::information(0, "", "连接主机成功");
}
